import { Link, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
import GlobalFilter from './GlobalFilter';
import './SalesDashboard.css';
import React, { useMemo, useState } from 'react';
import * as echarts from 'echarts';
import ReactECharts from 'echarts-for-react';
import MapboxMap from './MapboxMap';

const modules = [
  { key: 'filter', name: '全局筛选器模块' },
  { key: 'sales', name: '销售数据看板模块' },
  { key: 'map', name: '门店地图热力图模块' },
  { key: 'inventory', name: '库存告警与分析模块' },
  { key: 'trend', name: '趋势预测模块' },
  { key: 'permission', name: '权限控制模块' },
  { key: 'responsive', name: '响应式布局与大屏展示模块' },
];

function GlobalFilterModule() {
  // mock: 全局筛选条件（实际可用 context/store 传递）
  const [region, setRegion] = useState('');
  const [store, setStore] = useState('');
  const [dateRange, setDateRange] = useState(['', '']);

  // mock: 区域销售热力
  const mapData = [
    { name: '北京', value: 1200000, fullName: '北京市' },
    { name: '上海', value: 900000, fullName: '上海市' },
    { name: '广东', value: 800000, fullName: '广东省' },
    { name: '江苏', value: 600000, fullName: '江苏省' },
    { name: '浙江', value: 500000, fullName: '浙江省' },
    { name: '四川', value: 400000, fullName: '四川省' },
    { name: '重庆', value: 300000, fullName: '重庆市' }
  ];

  // 动态指标数据（真实项目可用接口返回）
  const regionMetrics: Record<string, any> = {
    北京:   { revenue: 1200000, profit: 120000, profitRate: 0.10, avgOrder: 6000, growth: 0.12, customers: 2000 },
    上海:   { revenue: 900000,  profit: 90000,  profitRate: 0.10, avgOrder: 5800, growth: 0.10, customers: 1800 },
    广东:   { revenue: 800000,  profit: 70000,  profitRate: 0.09, avgOrder: 5400, growth: 0.09, customers: 1700 },
    江苏:   { revenue: 600000,  profit: 60000,  profitRate: 0.10, avgOrder: 5200, growth: 0.08, customers: 1500 },
    浙江:   { revenue: 500000,  profit: 50000,  profitRate: 0.10, avgOrder: 5100, growth: 0.07, customers: 1400 },
    四川:   { revenue: 400000,  profit: 35000,  profitRate: 0.09, avgOrder: 4800, growth: 0.06, customers: 1200 },
    重庆:   { revenue: 300000,  profit: 25000,  profitRate: 0.08, avgOrder: 4700, growth: 0.05, customers: 1000 },
    '':     { revenue: 2681567, profit: 242192, profitRate: 0.09, avgOrder: 5247.69, growth: 0.14, customers: 6463 }, // 全部
  };
  const metrics = regionMetrics[region] || regionMetrics[''];

  // 处理区域变化
  const handleRegionChange = (newRegion: string) => {
    setRegion(newRegion);
  };

  // 动态趋势数据（真实项目可用接口返回）
  const regionTrends: Record<string, any> = {
    北京: {
      line: [120, 132, 101, 134, 90, 230, 210],
      bar: [320, 332, 301, 334, 390, 330, 320],
      pie: [
        { value: 1048, name: '饮料' },
        { value: 735, name: '零食' },
        { value: 580, name: '日用品' },
        { value: 484, name: '酒水' }
      ],
      radar: [
        { value: [4300, 10000, 28000, 35000, 50000, 19000], name: '本期' },
        { value: [5000, 14000, 28000, 31000, 42000, 21000], name: '同期' }
      ]
    },
    上海: {
      line: [100, 120, 110, 140, 80, 200, 180],
      bar: [300, 320, 290, 310, 350, 300, 310],
      pie: [
        { value: 900, name: '饮料' },
        { value: 800, name: '零食' },
        { value: 600, name: '日用品' },
        { value: 500, name: '酒水' }
      ],
      radar: [
        { value: [4000, 9000, 25000, 32000, 48000, 17000], name: '本期' },
        { value: [4800, 12000, 26000, 30000, 40000, 20000], name: '同期' }
      ]
    },
    广东: {
      line: [130, 140, 120, 150, 100, 250, 220],
      bar: [350, 340, 320, 360, 400, 350, 340],
      pie: [
        { value: 1100, name: '饮料' },
        { value: 700, name: '零食' },
        { value: 650, name: '日用品' },
        { value: 520, name: '酒水' }
      ],
      radar: [
        { value: [4500, 11000, 27000, 34000, 51000, 18000], name: '本期' },
        { value: [5200, 13000, 28000, 32000, 43000, 21000], name: '同期' }
      ]
    },
    江苏: {
      line: [110, 125, 115, 130, 95, 210, 200],
      bar: [310, 315, 305, 320, 370, 320, 315],
      pie: [
        { value: 950, name: '饮料' },
        { value: 780, name: '零食' },
        { value: 620, name: '日用品' },
        { value: 510, name: '酒水' }
      ],
      radar: [
        { value: [4200, 9500, 26000, 33000, 49000, 16000], name: '本期' },
        { value: [4700, 11000, 27000, 31000, 41000, 19000], name: '同期' }
      ]
    },
    浙江: {
      line: [115, 130, 120, 135, 100, 220, 210],
      bar: [320, 325, 310, 330, 380, 330, 320],
      pie: [
        { value: 980, name: '饮料' },
        { value: 760, name: '零食' },
        { value: 630, name: '日用品' },
        { value: 515, name: '酒水' }
      ],
      radar: [
        { value: [4300, 9800, 26500, 33500, 49500, 16500], name: '本期' },
        { value: [4800, 11500, 27500, 31500, 41500, 19500], name: '同期' }
      ]
    },
    四川: {
      line: [105, 120, 110, 125, 90, 200, 190],
      bar: [300, 310, 295, 315, 360, 310, 305],
      pie: [
        { value: 920, name: '饮料' },
        { value: 740, name: '零食' },
        { value: 610, name: '日用品' },
        { value: 505, name: '酒水' }
      ],
      radar: [
        { value: [4100, 9000, 25500, 32500, 48500, 15500], name: '本期' },
        { value: [4600, 10500, 26500, 30500, 40500, 18500], name: '同期' }
      ]
    },
    重庆: {
      line: [100, 115, 105, 120, 85, 190, 180],
      bar: [290, 300, 285, 305, 350, 300, 295],
      pie: [
        { value: 900, name: '饮料' },
        { value: 720, name: '零食' },
        { value: 600, name: '日用品' },
        { value: 500, name: '酒水' }
      ],
      radar: [
        { value: [4000, 8800, 25000, 32000, 48000, 15000], name: '本期' },
        { value: [4500, 10000, 26000, 30000, 40000, 18000], name: '同期' }
      ]
    },
    '': {
      line: [120, 132, 101, 134, 90, 230, 210],
      bar: [320, 332, 301, 334, 390, 330, 320],
      pie: [
        { value: 1048, name: '饮料' },
        { value: 735, name: '零食' },
        { value: 580, name: '日用品' },
        { value: 484, name: '酒水' }
      ],
      radar: [
        { value: [4300, 10000, 28000, 35000, 50000, 19000], name: '本期' },
        { value: [5000, 14000, 28000, 31000, 42000, 21000], name: '同期' }
      ]
    }
  };
  const trends = regionTrends[region] || regionTrends[''];
  const lineData = trends.line;
  const barData = trends.bar;
  const pieData = trends.pie;
  const radarData = trends.radar;

  // ECharts 其他卡片 option
  const lineOption = { xAxis: { type: 'category', data: ['1月','2月','3月','4月','5月','6月','7月'] }, yAxis: { type: 'value' }, series: [{ data: lineData, type: 'line', smooth: true, areaStyle: {} }] };
  const barOption = { xAxis: { type: 'category', data: ['A','B','C','D','E','F','G'] }, yAxis: { type: 'value' }, series: [{ data: barData, type: 'bar', barWidth: 18 }] };
  const pieOption = { tooltip: { trigger: 'item' }, legend: { top: '5%' }, series: [{ type: 'pie', radius: ['40%','70%'], data: pieData, label: { formatter: '{b}: {d}%'} }] };
  const radarOption = { tooltip: {}, legend: { top: 0 }, radar: { indicator: [ { name: '销售', max: 6500 }, { name: '管理', max: 16000 }, { name: '信息', max: 30000 }, { name: '研发', max: 38000 }, { name: '市场', max: 52000 }, { name: '客服', max: 25000 } ] }, series: [{ type: 'radar', data: radarData }] };

  return (
    <section style={{background:'#f8fafc',padding:'24px 32px',minHeight:'100vh'}}>
      <h3 className="dashboard-title">1. 全局筛选器模块</h3>
      <div className="dashboard-subtitle">多维度数据筛选，权限控制，实时更新</div>
      <div style={{marginBottom:24}}>
        {/* 筛选器可与下方数据联动，实际可用 context/store 传递 */}
        <GlobalFilter />
      </div>
      {/* 区域分布地图放大并置顶 */}
      <div style={{background:'#fff',borderRadius:12,boxShadow:'0 2px 12px rgba(0,0,0,0.06)',padding:24,marginBottom:32, width:'100%', maxWidth: '1200px', marginLeft: 'auto', marginRight: 'auto'}}>
        <div style={{fontWeight:600,marginBottom:8, fontSize:20}}>门店分布与热力图</div>
        <MapboxMap 
          selectedRegion={region} 
          onRegionChange={handleRegionChange}
          stores={[]}
        />
      </div>
      {/* 其他指标卡和趋势图整体放到地图下方 */}
      <div style={{display:'flex',flexWrap:'wrap',gap:24,justifyContent:'center'}}>
        {/* 指标区 */}
        <div style={{minWidth:320,background:'#fff',borderRadius:12,boxShadow:'0 2px 12px rgba(0,0,0,0.06)',padding:20,marginBottom:24,flex:'0 1 340px'}}>
          <div style={{fontSize:18,fontWeight:700,color:'#222',marginBottom:12}}>为高管提供的概览 - 盈利性 <span style={{fontSize:14,color:'#888'}}>(估值)</span></div>
          <div style={{display:'flex',flexDirection:'column',gap:8}}>
            <div style={{fontSize:16,fontWeight:600}}>营收：¥{metrics.revenue.toLocaleString()}</div>
            <div style={{fontSize:16,fontWeight:600}}>利润：¥{metrics.profit.toLocaleString()}</div>
            <div style={{fontSize:16,fontWeight:600}}>利润率：{(metrics.profitRate*100).toFixed(0)}%</div>
            <div style={{fontSize:16,fontWeight:600}}>客单价：¥{metrics.avgOrder.toLocaleString()}</div>
            <div style={{fontSize:16,fontWeight:600}}>增长率：{(metrics.growth*100).toFixed(0)}%</div>
            <div style={{fontSize:16,fontWeight:600}}>客户数：{metrics.customers.toLocaleString()}</div>
          </div>
        </div>
        {/* 趋势图区 */}
        <div style={{display:'flex',flexDirection:'column',gap:16,flex:'1 1 600px',minWidth:340}}>
          <div style={{display:'flex',gap:16}}>
            <div style={{flex:1,background:'#fff',borderRadius:12,boxShadow:'0 2px 12px rgba(0,0,0,0.06)',padding:16}}>
              <div style={{fontWeight:600,marginBottom:4}}>单客户净利润趋势</div>
              <ReactECharts option={lineOption} style={{width:'100%',height:100}} opts={{renderer:'svg'}} />
            </div>
            <div style={{flex:1,background:'#fff',borderRadius:12,boxShadow:'0 2px 12px rgba(0,0,0,0.06)',padding:16}}>
              <div style={{fontWeight:600,marginBottom:4}}>产品类别利润率趋势</div>
              <ReactECharts option={barOption} style={{width:'100%',height:100}} opts={{renderer:'svg'}} />
            </div>
          </div>
          <div style={{display:'flex',gap:16}}>
            <div style={{flex:1,background:'#fff',borderRadius:12,boxShadow:'0 2px 12px rgba(0,0,0,0.06)',padding:16}}>
              <div style={{fontWeight:600,marginBottom:4}}>产品类别销售额趋势</div>
              <ReactECharts option={pieOption} style={{width:'100%',height:100}} opts={{renderer:'svg'}} />
            </div>
            <div style={{flex:1,background:'#fff',borderRadius:12,boxShadow:'0 2px 12px rgba(0,0,0,0.06)',padding:16}}>
              <div style={{fontWeight:600,marginBottom:4}}>其他趋势</div>
              <ReactECharts option={radarOption} style={{width:'100%',height:100}} opts={{renderer:'svg'}} />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
function SalesBoardModule() {
  return (
    <section>
      <h3 className="dashboard-title">2. 销售数据看板模块</h3>
      <div className="dashboard-subtitle">销售趋势分析，业绩监控，数据可视化</div>
      <div className="module-placeholder">（此处为销售数据可视化内容）</div>
    </section>
  );
}
function MapHeatmapModule() {
  return (
    <section>
      <h3 className="dashboard-title">3. 门店地图热力图模块</h3>
      <div className="dashboard-subtitle">地理位置分析，门店分布，热力展示</div>
      <div className="module-placeholder">（此处为门店热力图内容）</div>
    </section>
  );
}
function InventoryAlertModule() {
  // mock 数据
  const data = [
    // { store: '北京一店', category: '饮料', stock: 8 }, // 移除
    // { store: '北京一店', category: '零食', stock: 18 },
    // { store: '北京一店', category: '日用品', stock: 14 },
    // { store: '北京一店', category: '酒水', stock: 11 },
    // { store: '上海一店', category: '饮料', stock: 5 },
    // { store: '上海一店', category: '零食', stock: 12 },
    // { store: '上海一店', category: '乳品', stock: 16 },
    // { store: '上海一店', category: '粮油', stock: 9 },
    { store: '广州店', category: '饮料', stock: 25 },
    { store: '广州店', category: '零食', stock: 22 },
    { store: '广州店', category: '水果', stock: 13 },
    { store: '广州店', category: '蔬菜', stock: 17 },
    { store: '深圳店', category: '日用品', stock: 15 },
    { store: '深圳店', category: '酒水', stock: 9 },
    { store: '深圳店', category: '乳品', stock: 21 },
    { store: '深圳店', category: '粮油', stock: 7 },
    { store: '杭州店', category: '蔬菜', stock: 17 },
    { store: '杭州店', category: '水果', stock: 13 },
    { store: '杭州店', category: '饮料', stock: 19 },
    { store: '杭州店', category: '零食', stock: 15 },
    { store: '成都店', category: '酒水', stock: 9 },
    { store: '成都店', category: '乳品', stock: 18 },
    { store: '成都店', category: '粮油', stock: 12 },
    { store: '成都店', category: '日用品', stock: 14 },
  ];
  // 动态生成门店和品类选项
  const storeSet = Array.from(new Set(data.map(d => d.store))).sort();
  const stores = ['全部', ...storeSet];
  const categorySet = Array.from(new Set(data.map(d => d.category))).sort();
  const categories = ['全部', ...categorySet];
  const [store, setStore] = useState('全部');
  const [category, setCategory] = useState('全部');
  const [severe, setSevere] = useState(10);
  const [warn, setWarn] = useState(20);
  // 过滤
  const filtered = data.filter(d => (store === '全部' || d.store === store) && (category === '全部' || d.category === category));
  // 级别
  function getLevel(stock: number): string {
    if (stock <= severe) return '严重';
    if (stock <= warn) return '警告';
    return '正常';
  }
  function getColor(level: string): string {
    if (level === '严重') return '#ff4d4f';
    if (level === '警告') return '#faad14';
    return '#52c41a';
  }
  // 条形图 option
  const barOption = useMemo(() => ({
    backgroundColor: 'rgba(255,255,255,0.0)',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(50,50,70,0.95)',
      borderRadius: 10,
      textStyle: { color: '#fff', fontWeight: 600 }
    },
    grid: { left: 30, right: 20, top: 30, bottom: 30 },
    xAxis: {
      type: 'category',
      data: filtered.map(d => d.store + '-' + d.category),
      axisLine: { lineStyle: { color: '#b3b8c3' } },
      axisLabel: { color: '#5a5e6b', fontWeight: 500, fontSize: 13 }
    },
    yAxis: {
      splitLine: { lineStyle: { color: '#f0f0f0' } },
      axisLine: { show: false },
      axisLabel: { color: '#5a5e6b', fontWeight: 500 }
    },
    series: [{
      type: 'bar',
      data: filtered.map(d => ({
        value: d.stock,
        itemStyle: {
          color: getColor(getLevel(d.stock)),
          borderRadius: [8, 8, 0, 0],
          shadowColor: 'rgba(0,0,0,0.08)',
          shadowBlur: 8
        }
      })),
      label: {
        show: true,
        position: 'top',
        color: '#333',
        fontWeight: 700,
        fontSize: 14,
        backgroundColor: 'rgba(255,255,255,0.7)',
        borderRadius: 6,
        padding: [2, 6]
      },
      barWidth: 16
    }]
  }), [filtered, severe, warn]);
  // 散点图 option
  const scatterOption = useMemo(() => ({
    backgroundColor: 'rgba(255,255,255,0.0)',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(50,50,70,0.95)',
      borderRadius: 10,
      textStyle: { color: '#fff', fontWeight: 600 }
    },
    grid: { left: 30, right: 20, top: 30, bottom: 30 },
    xAxis: {
      type: 'category',
      data: filtered.map(d => d.store),
      axisLine: { lineStyle: { color: '#b3b8c3' } },
      axisLabel: { color: '#5a5e6b', fontWeight: 500, fontSize: 13 }
    },
    yAxis: {
      splitLine: { lineStyle: { color: '#f0f0f0' } },
      axisLine: { show: false },
      axisLabel: { color: '#5a5e6b', fontWeight: 500 }
    },
    series: [{
      type: 'scatter',
      data: filtered.map(d => ({
        value: d.stock,
        itemStyle: {
          color: getColor(getLevel(d.stock)),
          shadowColor: 'rgba(0,0,0,0.12)',
          shadowBlur: 10
        }
      })),
      symbolSize: 12,
      label: {
        show: true,
        formatter: (p: any) => p.value,
        position: 'top',
        color: '#333',
        fontWeight: 700,
        fontSize: 14,
        backgroundColor: 'rgba(255,255,255,0.7)',
        borderRadius: 6,
        padding: [2, 6]
      }
    }]
  }), [filtered, severe, warn]);
  // 分页逻辑
  const [page, setPage] = useState(1);
  const pageSize = 5;
  const pageCount = Math.ceil(filtered.length / pageSize);
  const pagedData = filtered.slice((page-1)*pageSize, page*pageSize);
  // 翻页时重置到第1页
  React.useEffect(() => { setPage(1); }, [store, category, severe, warn]);
  return (
    <section>
      <h3 className="dashboard-title">4. 库存告警与分析模块</h3>
      <div className="dashboard-subtitle">实时监控库存状态，智能预警，数据分析</div>
      <div className="alarm-filter-bar">
        <label>门店：</label>
        <select value={store} onChange={e=>setStore(e.target.value)}>{stores.map(s=><option key={s}>{s}</option>)}</select>
        <label>品类：</label>
        <select value={category} onChange={e=>setCategory(e.target.value)}>{categories.map(c=><option key={c}>{c}</option>)}</select>
        <label>严重阈值：</label>
        <input type="number" value={severe} onChange={e=>setSevere(Number(e.target.value))} style={{width:60}} />
        <label>警告阈值：</label>
        <input type="number" value={warn} onChange={e=>setWarn(Number(e.target.value))} style={{width:60}} />
      </div>
      <div className="chart-container">
        <div className="chart-card">
          <div className="chart-title">库存告警分析图（ECharts）</div>
          <div className="merged-charts">
            <div className="chart-content">
              <ReactECharts option={barOption} style={{height: '100%', width: '100%'}} />
            </div>
            <div className="chart-content">
              <ReactECharts option={scatterOption} style={{height: '100%', width: '100%'}} />
            </div>
          </div>
        </div>
      </div>
      <div className="alarm-list-container">
        <div className="alarm-list-title">告警列表（分页，点击门店可跳转详情，示例）：</div>
        <div className="alarm-table-header">
          <span>门店</span>
          <span>品类</span>
          <span>库存</span>
          <span>级别</span>
        </div>
        {pagedData.map((d, i) => (
          <div key={i} className="alarm-table-row">
            <a href="#" className="alarm-link">{d.store}</a>
            <span>{d.category}</span>
            <span>{d.stock}</span>
            <span className={getLevel(d.stock)==='严重'?'level-severe':getLevel(d.stock)==='警告'?'level-warn':'level-normal'}>
              {getLevel(d.stock)}
            </span>
          </div>
        ))}
        <div className="pagination-container">
          <button 
            className="alarm-btn" 
            disabled={page<=1} 
            onClick={()=>setPage(p=>Math.max(1,p-1))}
          >
            上一页
          </button>
          <span className="pagination-info">{page}/{pageCount}</span>
          <button 
            className="alarm-btn" 
            disabled={page>=pageCount} 
            onClick={()=>setPage(p=>Math.min(pageCount,p+1))}
          >
            下一页
          </button>
        </div>
      </div>
    </section>
  );
}
function TrendForecastModule() {
  return (
    <section>
      <h3 className="dashboard-title">5. 趋势预测模块</h3>
      <div className="dashboard-subtitle">智能预测分析，趋势识别，决策支持</div>
      <div className="module-placeholder">（此处为趋势预测内容）</div>
    </section>
  );
}
function PermissionControlModule() {
  return (
    <section>
      <h3 className="dashboard-title">6. 权限控制模块</h3>
      <div className="dashboard-subtitle">角色权限管理，访问控制，安全防护</div>
      <div className="module-placeholder">（此处为权限控制内容）</div>
    </section>
  );
}
function ResponsiveLayoutModule() {
  return (
    <section>
      <h3 className="dashboard-title">7. 响应式布局与大屏展示模块</h3>
      <div className="dashboard-subtitle">多设备适配，大屏展示，用户体验优化</div>
      <div className="module-placeholder">（此处为响应式/大屏内容）</div>
    </section>
  );
}

export default function SalesDashboard() {
  const location = useLocation();
  const currentPath = location.pathname.slice(1); // 移除开头的 '/'
  
  return (
    <div className="dashboard-layout">
      <nav className="sidebar">
        <div className="nav-title">运营可视化分析平台</div>
        <div className="nav-section">
          {modules.map(m => (
            <Link 
              className={`nav-link ${currentPath === m.key ? 'active' : ''}`} 
              to={`/${m.key}`} 
              key={m.key}
            >
              {m.name}
            </Link>
          ))}
        </div>
      </nav>
      <main className="main-content">
        <Routes>
          <Route path="/filter" element={<GlobalFilterModule />} />
          <Route path="/sales" element={<SalesBoardModule />} />
          <Route path="/map" element={<MapHeatmapModule />} />
          <Route path="/inventory" element={<InventoryAlertModule />} />
          <Route path="/trend" element={<TrendForecastModule />} />
          <Route path="/permission" element={<PermissionControlModule />} />
          <Route path="/responsive" element={<ResponsiveLayoutModule />} />
          <Route path="*" element={<Navigate to="/filter" replace />} />
        </Routes>
      </main>
    </div>
  );
} 